import React from "react";
import { getBusinessData, changeContentField } from "src/utils/basic-business";
import { getSearchParams, merge } from "src/utils/index";
import rFormItems from "./process-doc";
import Detail from "pages/commonListView/detail";
import WorkflowCommit from "../commonListView/commit/workflow-commit";
import Form from "pages/components/form";
import { NavBar, Button, Toast, Dialog } from "antd-mobile";
import Btns from "pages/components/btns";
import { locationShape, historyShape, storeShape } from "src/propType";
import axios from "src/api/index";
import dayjs from "dayjs";
import SignTable from "../commonListView/signTable";
import FileList from "../components/fileList";
const buildOrgOptions = [
    {
        value: "1",
        label: "是",
    },
    {
        value: "2",
        label: "否",
    },
];

//过程文件
class ProcessDoc extends Detail {
    subForm = React.createRef();
    constructor(props) {
        super(props);
        const { store, location } = this.props;
        this.state = {
            ...this.state,
            formData: {
                wbsId: null,
            },
            formItems: rFormItems(this, getBusinessData(store, location, "projId")),
            selectedOptions: getBusinessData(store, location, "options"),
            baseUrl2: "pqsprojDataSet",
            uploading: false,
            childTabType: null, //用于区分工程类型的字段和切换子表
            status: "",
            signTitle: "wbsName",
            typeValSelect: null,
            useTypeOfWorkflow: getBusinessData(store, location, "tableId"), //传递参数，工作流formType
            isHaveType: 0, // 默认不配置清单项
            typeIdOptions: [],
            optionOne: null,
            random: 0,
            uploadShow: false,
            moduleTableId: null,

            dataSource: [],

            editVisible: false,
            selectRow: null,
            editType: "add",
            hasSubTable: false, //子表
        };
    }

    componentDidMount() {
        this.componentInit();
    }

    componentInit = () => {
        Promise.resolve(super.componentDidMount()).then(res => {
            this.setModules();
            this.initData();
        });
    };

    handleEditClick = row => {
        this.setState({
            selectRow: row,
            editVisible: true,
            editType: "edit",
        });
    };

    handleDeleteClick = async kid => {
        const isBack = await Dialog.confirm({ content: "此操作将永久删除数据, 是否继续?" });
        if (!isBack) return;
        axios({
            method: "post",
            url: "/pqsstartWkInSetTest_delete_one",
            data: { kid },
        }).then(res => {
            if (res.success) {
                Toast.show({
                    icon: "success",
                    content: "删除成功!",
                    duration: 1000,
                });
                this.getTableList();
            } else {
                Toast.show({
                    icon: "fail",
                    content: "删除失败!",
                    duration: 1000,
                });
            }
        });
    };

    getTableList = () => {
        const { formData, page, pageKid } = this.state;
        const joinId = formData?.kid || pageKid;
        if (!joinId) return;

        let data = {
            joinId,
            page: 1,
            limit: 100000,
        };
        axios({
            method: "get",
            url: "/pqsstartWkInSetTest_query_page",
            data,
        }).then(res => {
            if (res.success) {
                let dataSource = res.data.map(item => {
                    return {
                        ...item,
                        inDate: item.inDate && item.inDate.substring(0, 10),
                    };
                });
                this.setState({
                    dataSource,
                });
            } else {
                Toast.show({
                    icon: "fail",
                    content: res.msg,
                    duration: 1000,
                });
            }
        });
    };

    initData = () => {
        const { store, location } = this.props;
        const params = getSearchParams(location.search);
        let { formData, columns } = this.state;
        const moduleTableId = getBusinessData(store, location, "singleItem");
        const typeIdOptions = getBusinessData(store, location, "options");
        formData = {
            ...formData,
            moduleId: moduleTableId.tableId,
            moduleName: moduleTableId.modelName,
        };
        this.setState({
            formData,
            moduleTableId,
            typeIdOptions,
        });
        if (params.page === "add") {
            const selectedOptions = this.state.selectedOptions[0];
            const userData = store.user.userData;
            const optionOne = getBusinessData(store, location, "optionOne", selectedOptions?.value);
            formData = {
                ...formData,
                projTypeId: selectedOptions?.value, //业务id
                projTypeName: selectedOptions?.label, //业务label
                respUserId: userData.userId,
                respUserName: userData.name,
                addDate: new Date(),
                applyDate: new Date(),
                parentProjId: userData.projId,
                parentProjName: userData.projName,
            };
            if ([53, 55].includes(formData.projTypeId)) {
                formData = {
                    ...formData,
                    buildOrgId: "1", // 施工组织设计,主要人员变更,控制网评估申请使用
                    buildOrg: "是",
                };
            }

            if (formData.projTypeId === 21) {
                formData = {
                    ...formData,
                    remarkWork:
                        "请接桩单位接桩后尽快进行复测并妥善保护，接桩后一个月内将复测情况反馈给交桩单位，发现问题以书面形式反馈交桩单位，便于进行协商和妥善解决。",
                };
            }
            if (selectedOptions?.value !== 10 && selectedOptions?.value !== 11) {
                formData = {
                    ...formData,
                    stationSupMind: userData.projName,
                };
            }
            // 明细表
            if (selectedOptions?.isSubTable) {
                formData = {
                    ...formData,
                    signKid: selectedOptions?.isSubTable,
                };
            }
            this.setState(
                {
                    formData,
                    childTabType: selectedOptions?.value,
                    useTypeOfWorkflow: selectedOptions?.value,
                    optionOne,
                },
                () => {
                    this.changeTypeListTable();
                    this.initResponseField();
                    this.setHiddenForm(userData);
                    this.getTableList();
                    this.subForm.current?.form.setFieldsValue(formData);
                },
            );
        }
    };

    changeBuildOrg = val => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    buildOrg: val ? val.label : null,
                    buildOrgId: val ? val.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    changePactName = val => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    pactName: val ? val.label : null,
                    pactId: val ? val.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    changeCellName = val => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    cellName: val ? val.label : null,
                    cellId: val ? val.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    changeWbsName = val => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    wbsName: val ? val.label : null,
                    wbsId: val ? val.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    // 项目监理机构
    selectMontorName = org => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    monitorName: org ? org.label : null,
                    monitorId: org ? org.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    //   // 施工项目经理部
    selectMeasureOrgName = org => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    measureOrg: org ? org.label : null,
                    measureOrgId: org ? org.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    //  // 建设单位
    selectConsName = cons => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    consName: cons ? cons.label : null,
                    consId: cons ? cons.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    //   // 施工单位
    selectPactName = pact => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    consName: pact ? pact.label : null,
                    consId: pact ? pact.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    selectPact = pact => {
        let { formData } = this.state;
        this.setState(
            {
                formData: {
                    ...formData,
                    projName: pact ? pact.label : null,
                    projId: pact ? pact.value : null,
                },
            },
            () => this.initResponseField(),
        );
    };

    aftergetDetailData = resData => {
        const { store, location } = this.props;
        const {
            applyDate,
            cdate,
            planstartDate,
            planendDate,
            contractStartDate,
            contractEndDate,
            ...rest
        } = resData;
        let formData = {
            ...rest,
            applyDate: applyDate && dayjs(applyDate).toDate(),
            cdate: cdate && dayjs(cdate).toDate(),
            planstartDate: planstartDate && dayjs(planstartDate).toDate(),
            planendDate: planendDate && dayjs(planendDate).toDate(),
            contractStartDate: contractStartDate && dayjs(contractStartDate).toDate(),
            contractEndDate: contractEndDate && dayjs(contractEndDate).toDate(),
        };
        this.setState(
            {
                childTabType: formData.projTypeId,
                workflowModule: getBusinessData(
                    store,
                    location,
                    "workflowModule",
                    formData.projTypeId,
                ),
                useTypeOfWorkflow: formData.projTypeId,
                random: Math.random(),
                formData,
            },
            () => {
                this.subForm.current?.form.setFieldsValue(formData);
                this.getTableList();
                this.setHiddenForm();
                this.changeTypeListTable();
            },
        );
    };

    handleFormDataBeforeSave = values => {
        const { formData, ajaxData, isNoChangeStateId, page } = this.state;
        const {
            cdate,
            applyDate,
            planstartDate,
            planendDate,
            contractStartDate,
            contractEndDate,
            ...rest
        } = values;
        if (cdate && typeof cdate !== "string") {
            values.cdate = this.formatDateTime(cdate);
        }
        if (applyDate && typeof applyDate !== "string") {
            values.applyDate = this.formatDateTime(applyDate);
        }
        if (planstartDate && typeof planstartDate !== "string") {
            values.planstartDate = this.formatDateTime(planstartDate);
        }
        if (planendDate && typeof planendDate !== "string") {
            values.planendDate = this.formatDateTime(planendDate);
        }
        if (contractStartDate && typeof contractStartDate !== "string") {
            values.contractStartDate = this.formatDateTime(contractStartDate);
        }
        if (contractEndDate && typeof contractEndDate !== "string") {
            values.contractEndDate = this.formatDateTime(contractEndDate);
        }
        let change = {
            ...formData,
            ...rest,
            ...values,
        };
        merge(change, ajaxData);
        if (isNoChangeStateId) {
            // 开工标准化，审核后编辑，不更新状态
            delete change.stateId;
            delete change.stateName;
            if (page === "add") {
                delete change.moduleId;
            }
        }
        return change;
    };

    projTypeIdChange = val => {
        const { formData, page, selectedOptions } = this.state;
        const { store, location } = this.props;
        const { label, value } = val;
        const newValue = {
            ...formData,
            projTypeId: value,
            projTypeName: label,
        };

        if (newValue.optionOne?.isSubTable) {
            newValue["signKid"] = newValue.optionOne.isSubTable ? 1 : null;
        }
        this.setState(
            {
                formData: newValue,
                optionOne: getBusinessData(store, location, "optionOne", value),
                typeValSelect: selectedOptions.find(opt => opt.value === value),
                workflowModule: getBusinessData(store, location, "workflowModule", value),
                useTypeOfWorkflow: value,
                childTabType: value,
            },
            () => {
                this.initResponseField();
                this.subForm.current?.form.setFieldsValue(newValue);
                this.changeTypeListTable();
                this.setHiddenForm();
            },
        );
    };

    editVisibleCb = refresh => {
        this.setState({
            editVisible: false,
        });
        refresh && this.getTableList();
    };

    onValuesChange = (changedValues, allValues) => {
        console.log(changedValues, allValues);
        const {buildOrgUser, measureOrgUser, monitorUser, consUser} = changedValues;
        if(buildOrgUser || measureOrgUser || monitorUser || consUser) {
            this.initResponseField();
        }
    };


    render() {
        const {
            formItems,
            formData,
            options,
            // columns,
            dataSource,
            baseUrl,
            useTypeOfWorkflow,
            workflowModule,
            useWorkflow,
            page,
            pageKid,
            title,
            hasSubTable,
            baseUrl2,
            isHaveType,
            childTabType,
            moduleId,
            editVisible,
            selectRow,
            editType,
        } = this.state;
        const { store, location, history } = this.props;
        const { projId, pactId, userId } = store.user.userData;

        const btns = [
            {
                label: "确认审核",
                key: "1",
                fn: () => {
                    this.commitSign();
                },
                hidden: () => page !== "sign",
            },
            {
                label: "提交审核",
                key: "2",
                fn: () => {
                    this.commit();
                },
                hidden: () => !["edit", "add"].includes(page),
            },
            {
                label: "保存草稿",
                key: "3",
                fn: () => this.save(),
                hidden: () => !["edit", "add"].includes(page),
            },
            {
                label: "预览",
                key: "4",
                fn: () => this.toViewPdf(formData),
                hidden: () => page === "add",
            },
        ];

        const optionOne =
            getBusinessData(store, location, "optionOne", useTypeOfWorkflow) ||
            getBusinessData(
                store,
                location,
                "optionOne",
                getBusinessData(store, location, "tableId"),
            );

        let workflowModuleCur = workflowModule;
        if (useWorkflow) {
            workflowModuleCur = workflowModule + "-" + (formData[useWorkflow] || 1);
        }


        return (
            <div className="detail-container">
                <NavBar back="返回" onBack={() => this.props.history.go(-1)}>
                    {title}
                </NavBar>
                <Form
                    subtitle="基本信息"
                    formItems={formItems}
                    formData={formData}
                    projId={projId}
                    pactId={pactId}
                    options={options}
                    selectCallBack={{
                        selectPact: this.selectPact,
                        projTypeIdChange: this.projTypeIdChange,
                        changeBuildOrg: this.changeBuildOrg,
                        changePactName: this.changePactName,
                        changeCellName: this.changeCellName,
                        changeWbsName: this.changeWbsName,
                        selectMontorName: this.selectMontorName,
                        selectMeasureOrgName: this.selectMeasureOrgName,
                        selectConsName: this.selectConsName,
                        selectPactName: this.selectConsName,
                    }}
                    buildOrgOptions={buildOrgOptions}
                    ref={this.subForm}
                    initSelect={page === "add"}
                    status={page}
                    formDisabled={["view", "sign"].includes(page)}
                    onValuesChange={this.onValuesChange}
                >
                    {isHaveType ? (
                        <FileList
                            infoKid={pageKid}
                            url={baseUrl2}
                            moduleId={moduleId}
                            typeId={childTabType}
                            detailPage={page}
                            wbsId={formData.wbsId}
                            user={store.user.userData}
                        />
                    ) : null}
                </Form>
                <WorkflowCommit
                    ref={this.workflowRef}
                    baseUrl={baseUrl}
                    formData={formData}
                    optionOne={optionOne}
                    workflowModule={workflowModuleCur}
                    projId={projId}
                    userData={store.user.userData}
                    page={page}
                    kid={pageKid}
                    commitCallBack={this.commitCallBack}
                />
                <SignTable
                    ref={this.signRef}
                    optionOne={optionOne}
                    userId={userId}
                    addUserId={formData.addUserId}
                    kid={pageKid}
                    commitSignCallBack={this.commitCallBack}
                />
                {/* <EditForm
                    visible={editVisible}
                    visibleCb={this.editVisibleCb}
                    projTypeId={formData.projTypeId}
                    row={selectRow}
                    editType={editType}
                    state={this.state}
                    formDisabled={["view", "sign"].includes(page)}
                /> */}
                <Btns btns={btns} size="large" block />
            </div>
        );
    }
}

ProcessDoc.propTypes = {
    store: storeShape,
    history: historyShape,
    location: locationShape,
};

export default ProcessDoc;
